package concole;

import java.io.BufferedReader;
import java.io.FileReader;

public class RegisterLogic {
	int idInt;
	String num;
	String password;
	String FileName;
	String[] inputInfo;
	String name;
	boolean canRegister=false;

	public RegisterLogic() {
	}

	public RegisterLogic(int idInt, String[] inputInfo) {
		this.idInt = idInt;
		this.FileName = (idInt == 2) ? "teacherAccounts.txt"
				: "studentAccounts.txt";
		this.inputInfo = inputInfo;
		try {
			this.num = inputInfo[2].substring(1, inputInfo[2].indexOf("]"));
			this.password = inputInfo[3]
					.substring(1, inputInfo[3].indexOf("]"));
			canRegister=true;
		} catch (Exception e) {
			System.out.println("sorry error happens Please check your format");
			return;
		}
	}

	public void go() {

		if (!ifExisted()&&this.canRegister) {
			IOHelper.addOneLine(this.FileName, this.num + " " + this.password);
			System.out.println("Please input your name");
		} else {
			return;
		}

		this.name = IOHelper.readConsoleNextLine();
		if (this.idInt == 2) {
			IOHelper.addOneLine("teachersList.txt", this.num + " " + this.name);
		} else {
			IOHelper.addOneLine("studentsList.txt", this.num + " " + this.name);
		}

	}

	public boolean checkFormat() {
		boolean formatRight = false;
		if (this.inputInfo.length != 4) {
			System.out.println("Sorry format Error");
			return formatRight;
		}

		return formatRight;
	}

	public boolean ifExisted() {
		boolean ifExisted = false;
		try {

			FileReader fReader = new FileReader(this.FileName);
			BufferedReader bf = new BufferedReader(fReader);
			// StringBuffer strBf = new StringBuffer();
			String record;
			while ((record = bf.readLine()) != null) {
				// strBf.append(record);
				String[] fileRecord = record.split(" ");
				if (fileRecord[0].equals(this.num)) {
					System.out.println("Sorry the account has existed");
					ifExisted = true;
				}
			}
			bf.close();
		} catch (Exception e) {
			System.out.println("Sorry ERROR");
		}
		return ifExisted;
	}

}
